<?php
namespace App\Services\Zto;


class ZtoApi implements ZtoContract{
	/**
	 * HTTP请求超时时间
	 */
	protected $timeout = 5;

	protected $url = 'http://japi.zto.cn/zto/api_utf8/traceInterface';

	protected $key = '9522B4DECFF9F16AEE4B047BDFE413E6';

	protected $company_id = 'a7ca926cdd5e42f78cfd69bfb4827969';

	/**
	 * 获取物流轨迹
	 */
	public function getLogisticsTrajectory($bill_codes)
	{
		// 忽略单元测试环境。
		if (app()->runningUnitTests()) {
			return false;
		}

		$post_data = $this->getPostData($bill_codes,'TRACES');

		$result = $this->httpPost($this->url,$post_data);

		// 检查返回。
		return $result;
	}

	public function getDataDigest($bill_codes)
	{
		$data_digest = md5(json_encode($bill_codes,true).$this->key);
		$encode = mb_detect_encoding($data_digest);
		$data_digest = mb_convert_encoding($data_digest, 'UTF-8', $encode); 

		return $data_digest;
	}

	public function getPostData($bill_codes,$msg_type)
	{
		$data_digest = $this->getDataDigest($bill_codes);
		$post_data = [
			'data' => json_encode($bill_codes),
			'data_digest' => $data_digest,
			'msg_type' => $msg_type,
			'company_id' => $this->company_id
		];

		return $post_data;
	}

	/**
	 * GET方法请求HTTP
	 *
	 * @param string $url
	 * @param array $data
	 */
	protected function httpGet($url, $data = [])
	{
		return $this->httpRequest('GET', $url, $data);
	}

	/**
	 * POST方法请求HTTP
	 *
	 * @param string $url
	 * @param array $data
	 */
	protected function httpPost($url, $data = [])
	{
		return $this->httpRequest('POST', $url, $data);
	}

	/**
	 * 基础HTTP请求实现
	 * @param string $method
	 * @param string $url
	 * @param array $data
	 * @return string
	 */
	private function httpRequest($method, $url, $data)
	{
		$method = strtoupper($method);
		if (! in_array($method, [
			'GET',
			'POST'
		])) {
			$method = 'GET';
		}

		$response = false;
		try {

			$data = http_build_query($data);

			$opts = [
				'http' => [
					'method' => $method,
					'timeout' => $this->timeout
				]
			];

			switch ($method) {
				case 'GET':
					$url .= strpos($url, '?') === false ? '?' : '&';
					$url .= $data;
					break;
				case 'POST':
					$opts['http']['header'] = "Content-type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($data) . "\r\n";
					$opts['http']['content'] = $data;
					break;
			}

			$context = stream_context_create($opts);
			$response = file_get_contents($url, false, $context);
		} catch (\Exception $e) {
			// 捕获异常。
			// throw $e;
			// TODO: 记录错误日志，静默处理。
		}

		// 剔除前后空格。
		$response = preg_replace('/^\\s+|\\s+$/', '', $response);

		return $response;
	}
}
?>